package com.lovezy.platform.discuz.service.impl;

import com.lovezy.platform.core.base.query.Pager;
import com.lovezy.platform.core.codec.CodecUtil;
import com.lovezy.platform.core.exception.ServiceException;
import com.lovezy.platform.core.mybatis.MapperHelper;
import com.lovezy.platform.discuz.mapper.DiscuzMemberMapper;
import com.lovezy.platform.discuz.model.DiscuzMember;
import com.lovezy.platform.discuz.model.DiscuzMemberExample;
import com.lovezy.platform.discuz.service.DiscuzMemberService;
import com.lovezy.platform.discuz.vo.DiscuzMemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Optional;

import static com.lovezy.platform.core.utils.ObjectUtil.copy;

/**
 * Created by jin on 2017/11/3.
 */
@Service
public class DiscuzMemberServiceImpl implements DiscuzMemberService{

    @Autowired
    @Qualifier("discuzMapperHelper")
    private MapperHelper mapperHelper;

    public DiscuzMember selectById(Integer id) {
        return mapperHelper.callMapper(DiscuzMemberMapper.class, mapper -> mapper.selectByPrimaryKey(id));
    }

    @Override
    public DiscuzMemberVo login(String username, String password) {
        DiscuzMemberExample example = new DiscuzMemberExample();
        example.createCriteria()
                .andUsernameEqualTo(username);
        Optional<DiscuzMember> dzMemberOpt = mapperHelper.callMapper(DiscuzMemberMapper.class, mapper -> Pager.doSingleton(() -> mapper.selectByExample(example)));
        if (!dzMemberOpt.isPresent()) {
            throw new ServiceException("DZ-MEMBER_NOT_FOUND", "论坛账户不存在！");
        }
        DiscuzMember member = dzMemberOpt.get();
        String salt = member.getSalt();
        String realPassword = member.getPassword();
        if (!realPassword.equals(CodecUtil.md5(password + salt))) {
            throw new ServiceException("DZ-MEMBER_PASSWORD_ERROR", "论坛账户密码错误！");
        }
        DiscuzMemberVo memberVo = new DiscuzMemberVo();
        copy(member, memberVo);
        return memberVo;
    }

}
